package com.atguigu.tingshu.order.consumer;

import com.atguigu.tingshu.order.service.OrderInfoService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/***
 * 订单超时取消延迟信息消费者
 */
@Component
@Log4j2
public class OrderDelayMessageConsumer {
    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private RedisTemplate redisTemplate;

    @SneakyThrows
    @RabbitListener(queues = "order_delay_queue")
    public void timeOutCancelOrder(Channel channel, Message message){
        // 获取信息内容(OrderNo + UserId)
        String orderNo = new String(message.getBody());
        // 获取信息属性
        MessageProperties messageProperties = message.getMessageProperties();
        // 获取信息编号
        long deliveryTag = messageProperties.getDeliveryTag();
        try {
            orderInfoService.cancelOrder(orderNo);
            channel.basicAck(deliveryTag,false);
        }catch (Exception e){
            // 判断信息是否是第一次被消费
            if (messageProperties.getRedelivered()){
                // 是重试订单 将错误日志记录到redis后丢弃消息
                redisTemplate.opsForSet().add("timeOutCancelOrderFailed: ",orderNo);
                channel.basicReject(deliveryTag,false);
            }else {
                // 拒绝后返回 重新消费
                channel.basicReject(deliveryTag,true);
            }
        }
    }




//
//    todo - afterPaid -- 增加专辑或声音的购买次数
//    public void afterPaid(Channel channel, Message message){
//
//        try {
//            修改专辑或信息的购买次数 -- feign调用修改信息
//            channel.basicAck(deliveryTag,false);
//        }catch (Exception e){
//                channel.basicReject(deliveryTag,false);
//            }else {
//                // 拒绝后返回 重新消费
//                channel.basicReject(deliveryTag,true);
//            }
//        }
//    }




}
